const redis = require('redis')
const { REDIS_CONFIG } = require('../config/db')

// 创建客户端
const redisClient = redis.createClient(REDIS_CONFIG.port, REDIS_CONFIG.host)
redisClient.on('error', err => {
  console.log('redisClient-error', err)
})

// 设置redis
function set(key, val) {
  if (typeof val === 'object') {
    val = JSON.stringify(val)
  }
  console.log('set', key, val)
  redisClient.set(key, val, redis.print)
}

// 获取redis指定key的值
function get(key) {
  return new Promise((resolve, reject) => {
    redisClient.get(key, (err, val) => {
      console.log('get', key, err, val)
      if(err) {
        reject(err)
      }

      try{
        resolve(JSON.parse(val))
      }catch(err) {
        resolve(val)
      }
    })
  })
}

module.exports = {
  set,
  get
}